package nsoft.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nsoft.swing.annotation.AComponent;
import nsoft.swing.annotation.APanel;
@APanel(name = "RootPane", layout = "FlowLayout(1)")
public class UiModel implements Serializable{
	/**
	 *	serialVersionUID = 5091046677477173933L;
	 */
	public static final long serialVersionUID = 5091046677477173933L;

	private static final String DOT = ".";

	private static final String EMPTY = "";

	protected String viewModelId;

	private Object modelBean;

	private Map<String, List<Object>> beanMap = new HashMap<String,List<Object>>();

	public UiModel(String viewModelId, Object bean) {
		this(viewModelId);
		modelBean = bean;
		// addBean(bean, name);
	}

	public UiModel(String viewModelId) {
		this.viewModelId = viewModelId;
		modelBean = this;
	}

	public Object getValue(String property) {
		Object value = BeanUtilities.getPropertyD(this, property);
		if (value == null && property != null && property.contains(DOT)) {
			value = BeanUtilities.getPropertyD(beanMap.get(property.substring(
					0, property.indexOf(DOT))), property.substring(property
					.indexOf(DOT) + 1));
		}
		return value;
	}

	public String getValueString(String property) {
		Object val = getValue(property);
		return FormatUtil.format((val == null ? EMPTY : val));
	}

	public Object createProperty(String property) {
		return new Property(this, property);
	}

	public String getViewModelId() {
		return viewModelId;
	}

	public void setViewModelId(String viewModelId) {
		this.viewModelId = viewModelId;
	}

	public void addBean(Object bean, String parentName) {
		if(!beanMap.containsKey(parentName)){
			beanMap.put(parentName,new ArrayList<Object>());
		}
		beanMap.get(parentName).add(bean);
	}

	public void addBean(Object bean) {
		if (bean == null) {
			return;
		}
		APanel panel = bean.getClass().getAnnotation(APanel.class);
		if (panel != null && !panel.parent().equals(EMPTY)) {
			addBean(bean, panel.parent());
		} else {
			AComponent component = bean.getClass().getAnnotation(
					AComponent.class);
			if (component != null && !component.parent().equals(EMPTY)) {
				addBean(bean, component.parent());
			}
		}
	}

	public Map<String, List<Object>> getBeanMap() {
		return beanMap;
	}

	public Object getModelBean() {
		return modelBean;
	}

	public void setModelBean(Object modelBean) {
		this.modelBean = modelBean;
	}

}
